package ConnectionsCommands;

import Connections.DownloaderClient;
import Connections.Tracker;
import Gear.Factory;

import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Implement received command to inform a random peer that contains a file.
 *
 * @author Rodrigo Martins Racanicci
 */
public class ConnectionCommandRequestPeer implements ConnectionCommand {

    @Override
    public void execute(Socket client, String[] args) {
        try {
            Factory.getInstance().getTracker().getFileMutex().acquire();
            Tracker t = Factory.getInstance().getTracker();

            String peer = t.requestPeer(args[1]);
            while (peer != null) {

                try {
                    DownloaderClient d = new DownloaderClient(peer);
                    d.sendCommand("Close");
                    d.close();
                    break;
                } catch (RuntimeException e) {
                    Factory.getInstance().getTracker().removeHost(peer);
                }

                peer = t.requestPeer(args[1]);
            }

            t.sendCommand(client, t.requestPeer(args[1]));
            t.closeClient(client);
            Factory.getInstance().getTracker().getFileMutex().release();
        } catch (InterruptedException ex) {
            Logger.getLogger(ConnectionCommandRequestPeer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
